<template>
  <div>
    <el-card shadow="never">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="18" :lg="18" :md="18" :sm="24" :xs="24">
            <div class="flex items-center">
              <div>
                <div class="text-20px">
                  案件名称：{{ caseName ?? '加载中...' }}
                </div>
                <div v-if="description" class="mt-10px text-14px text-gray-500"
                     v-html="safeDescription"></div>
                <div v-else class="mt-10px text-14px text-gray-500">
                  暂无案件描述
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">
      <!-- 涉及人员卡片区域 - 优化局部刷新 -->
      <el-card shadow="never" class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between items-center">
            <div class="header-title">
              <span>涉及人员</span>
              <el-button
                type="primary"
                link
                size="small"
                @click="showPersonList = true"
                class="add-btn"
              >
                <Icon icon="ep:plus" class="mr-1"/>
                添加
              </el-button>
            </div>
            <el-pagination
              small
              layout="prev, pager, next"
              :total="total"
              :page-size="queryParams.pageSize"
              :current-page="queryParams.pageNo"
              @current-change="handlePersonPageChange"
              :pager-count="5"
              class="person-pagination"
            />
          </div>
        </template>
        <!-- 添加key实现分页变化时只更新该区域 -->
        <div :key="`person-list-${queryParams.pageNo}`">
          <el-skeleton :loading="loading" animated>
            <el-row>
              <el-col
                v-for="(item, index) in list"
                :key="`card-${item.id || index}`"
                :xl="8"
                :lg="8"
                :md="8"
                :sm="24"
                :xs="24"
              >
                <el-card shadow="hover" class="mr-5px mt-5px relative">
                  <!-- 右上角徽标 -->
                  <div class="absolute right-10px top-10px bottom-5px flex space-x-2">
                    <el-badge :value="item.unreadTotal" title="未读预警数量" type="danger"
                              class="custom-badge"/>
                    <el-badge :value="item.warnCount" title="总预警数量" type="info"
                              class="custom-badge"/>
                  </div>
                  <div class="flex items-start"> <!-- 使用items-start确保顶部对齐 -->
                    <!-- 头像区域 -->
                    <div @click="openMemberDetail(item.id)" class="cursor-pointer mr-4">
                      <img :src="item.avatar" style="width: 50px; height: 50px;" alt="用户头像"/>
                    </div>

                    <!-- 右侧文本区域 -->
                    <div class="flex-1 min-w-0">
                      <!-- 第一行：姓名和群组标签 -->
                      <div class="flex items-center flex-wrap gap-2 mb-1">
                        <span class="text-16px font-medium truncate">{{ item.name }}</span>
                        <div v-if="item.groupName"
                             class="text-13px bg-blue-50 text-blue-600 px-3 py-1 rounded-full shadow-sm border border-blue-100">
                          {{ item.groupName }}
                        </div>
                      </div>

                      <!-- 第二行：证件号码 -->
                      <div v-if="item.paperNumber" class="text-12px text-gray-500">
                        {{ item.paperNumber }}
                      </div>
                    </div>
                  </div>

                  <div class="mt-12px flex justify-between text-12px text-gray-400">
                    <span>{{ item.lastLocation }}</span>
                    <span>{{ item.lastLocationTime }}</span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-skeleton>
        </div>
      </el-card>

      <el-drawer
        v-model="showPersonList"
        title="添加涉案人员"
        direction="rtl"
        size="50%"
      >
        <!-- 标题下方的阴影分隔线 -->
        <div class="header-divider"></div>

        <!-- 人员列表组件 -->
        <PersonListDrawer
          :case-id="String(route.params.id)"
          @cancel="showPersonList = false"
        />
      </el-drawer>

      <el-card shadow="never" class="mt-8px">
        <el-skeleton :loading="loading" animated>
          <el-row :gutter="20" justify="space-between">
            <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <el-skeleton :loading="loading" animated>
                  <Echart :options="pieOptionsData" :height="280"/>
                </el-skeleton>
              </el-card>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never" class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between items-center flex-wrap gap-4">
            <div class="header-title">
              <span>最新预警</span>
            </div>
            <el-pagination
              small
              layout="prev, pager, next"
              :total="warnTotal"
              :current-page="queryWarnParams.pageNo"
              @current-change="handleWarnPageSizeChange"
              class="person-pagination"
              :pager-count="3"
            />
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <!-- 通知列表部分保持不变 -->
          <div v-for="(item, index) in warnList" :key="`dynamics-${index}`">
            <div class="flex items-start">
              <!-- 头像区域 -->
              <el-avatar :size="35" class="mr-16px mt-2 cursor-pointer" @click="openMemberDetail(item.personId)">
                <img
                  :src="item.avatar || require('../../../../assets/imgs/avatar.gif')"
                  alt="用户头像"
                  @error="item.avatar = require('../../../../assets/imgs/avatar.gif')"
                />
              </el-avatar>

              <!-- 右侧文本区域 -->
              <div class="flex-1">
                <!-- 人员姓名 -->
                <div class="text-14px font-medium text-gray-800 mb-1 flex items-center">
                  <span>{{ item.personName || '未知人员' }}</span>
                  <span class="text-12px text-gray-400 ml-3 truncate">{{ item.idNumber || '未填写' }}</span>
                </div>

                <!-- 预警类型和内容 -->
                <div class="text-14px mb-1">
                  <Highlight :keys="item.keys" @click="openGatherDetail(item)">
                    【{{ item.type }}】 {{ item.title }} {{ item.warnPersonCountText}}
                  </Highlight>
                </div>

                <!-- 时间信息 -->
                <div class="text-12px text-gray-400">
                  {{ formatTime(item.date, 'yyyy-MM-dd HH:mm:ss') }}
                </div>
              </div>
            </div>
            <el-divider v-if="index !== warnList.length - 1"/>
          </div>

          <!-- 空状态处理 -->
          <div v-if="!loading && warnList.length === 0" class="text-center py-10">
            <div class="text-gray-400">暂无预警记录</div>
          </div>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {useI18n} from 'vue-i18n'
import {set} from 'lodash-es'
import {EChartsOption} from 'echarts'
import DOMPurify from 'dompurify'
// 确保已安装此依赖
import {CasesApi, UnifiedWarningDTO, WarningTypeCountDTO} from '@/api/member/cases'
import {formatTime} from '@/utils'
import {PersonCaseInfo, PersonTotal, Shortcut, WarnCommon} from './types'
import {barOptions, pieOptions} from './echarts-data'
import PersonListDrawer from '../components/PersonListDrawer.vue'
import Echart from "../../../../components/Echart/src/Echart.vue";
import Highlight from '@/components/Highlight/src/Highlight.vue' // 假设你有这个高亮组件
import Icon from '../../../../components/Icon/src/Icon.vue' // 确保图标组件存在
import * as UserApi from '@/api/member/user'
import {useMessage} from "@/hooks/web/useMessage";

defineOptions({name: 'CaseDetail'})

// 控制抽屉显示
const showPersonList = ref(false)

const {t} = useI18n()
const route = useRoute()
const router = useRouter()

// 案件数据
const caseData = ref<any>(null)
const caseName = ref('')
const description = ref('')

// 分页数据 - 统一使用queryParams管理
const loading = ref(true)
const listLoading = ref(true)
const total = ref(0)
const warnTotal = ref(0)
const list = ref<PersonCaseInfo[]>([])
const message = useMessage()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 12,
  caseId: route.params.id,
})

// 图表数据
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 统计数
const totalSate = reactive<PersonTotal>({
  person: 90,
  warn: 20,
})

// 通知公告
const warnList = reactive<WarnCommon[]>([])
const shortcut = reactive<Shortcut[]>([])

// 安全处理HTML内容
const safeDescription = computed(() => {
  return DOMPurify.sanitize(description.value)
})

// 获取案件详情
const fetchCaseData = async (id: string) => {
  try {
    const res = await CasesApi.getCases(id)
    caseData.value = res
    caseName.value = res.caseName
    description.value = res.description
  } catch (error) {
    console.error('获取案件详情失败:', error)
  }
}

/** 查询列表 - 只更新人员列表数据 */
const getList = async () => {
  listLoading.value = true
  try {
    const data = await UserApi.getCaseUserPage(queryParams)
    list.value = data.list // 仅更新列表数据
    total.value = data.total
  } finally {
    listLoading.value = false
  }
}

// 分页变化处理 - 仅更新分页参数并刷新列表
const handlePersonPageChange = (page: number) => {
  queryParams.pageNo = page
  getList() // 只重新获取人员列表，不影响其他组件
}

const handleWarnPageSizeChange = (page: number) => {
  queryWarnParams.pageNo = page
  getWarnPage()
}

// 获取统计数据
const getCount = async () => {
  totalSate.person = 9
  totalSate.warn = 2340
}

const openMemberDetail = (id: number) => {
  router.push({name: 'MemberUserDetail', params: {id}})
}

const queryWarnParams = reactive({
  pageNo: 1,
  pageSize: 8,
  caseId: route.params.id,
})

// 获取通知公告 - 修改为调用真实API
const getWarnPage = async () => {
  warnList.length = 0
  try {

    // 调用API获取最新预警数据
    const response = await CasesApi.getCaseLatestWarnPage(queryWarnParams)
    const warnings: UnifiedWarningDTO[] = response.list;
    warnTotal.value = response.total;

    // 转换为页面所需的格式
    warnings.forEach(warn => {
      // 确定预警类型文本
      let warnTypeText: string
      let gatherPersonCountText = ''
      switch (warn.warnType) {
        case 1:
          warnTypeText = '围栏预警'
          break
        case 2:
          warnTypeText = '聚集预警'
          gatherPersonCountText = '聚集人数：'+ warn.warnPersonCount
          break
        case 3:
          warnTypeText = '出入杭预警'
          break
        case 4:
          warnTypeText = '接入预警'
          break
        default:
          warnTypeText = '未知预警'
      }

      // 确定预警内容
      let content = warn.warningContent || `定位地址: ${warn.address || '未知'}`

      // 确定时间字段（优先使用预警时间，没有则使用定位时间）
      const time = warn.warningTime || warn.locationTime
      warnList.push({
        title: content,
        type: warnTypeText,
        keys: [warnTypeText, ...content.split(/\s+/), gatherPersonCountText],
        date: time ? new Date(time) : new Date(),
        idNumber: warn.idNumber,
        personName: warn.personName,
        avatar: warn.avatar,

        personId: warn.personId,
        gatherId: warn.gatherId,
        configId: warn.configId,
        address: warn.address,
        warnPersonCountText: gatherPersonCountText,
        warnPersonCount: warn.warnPersonCount,
        gatherName: warn.gatherName, // 聚集条件名称
        startTime: warn.startTime, // 聚集开始时间
        endTime: warn.endTime, // 聚集结束时间
        gatherAddress: warn.gatherAddress, // 聚集地址
        createTime: warn.createTime
      })
    })
  } catch (error) {
    console.error('获取最新预警失败:', error)
  }
}

// 获取快捷入口
const getShortcut = async () => {
  shortcut.length = 0
  shortcut.push(...[
    {
      name: 'Github',
      icon: 'akar-icons:github-fill',
      url: 'github.io'
    }
  ])
}

// 用户来源图表
const getWarnTypePie = async () => {
  try {
    // 调用后端API获取真实数据
    const caseId = Array.isArray(route.params.id) ? route.params.id[0] : route.params.id;
    const response = await CasesApi.countTodayWarningsByType(caseId);

    if (response) {
      // 格式化数据用于饼图
      const pieList: WarningTypeCountDTO[] = response;
      const data = pieList.map(item => ({
        value: item.count,
        name: item.warnTypeName,
        warnType: item.warnType
      }));

      // 更新图表数据
      set(pieOptionsData, 'legend.data', data.map(v => t(v.name)));
      pieOptionsData.series![0].data = data.map(v => ({
        name: t(v.name),
        value: v.value
      }));
    } else {
      console.error('获取预警类型统计失败', response);
      // 显示默认数据
      const defaultData = [
        {value: 335, name: '围栏预警', warnType: 1},
        {value: 310, name: '聚集预警', warnType: 2},
        {value: 234, name: '出入杭预警', warnType: 3},
        {value: 24, name: '接入预警', warnType: 4},
      ];
      set(pieOptionsData, 'legend.data', defaultData.map(v => t(v.name)));
      pieOptionsData.series![0].data = defaultData.map(v => ({
        name: t(v.name),
        value: v.value
      }));
    }
  } catch (error) {
    console.error('获取预警类型统计异常', error);
    // 显示默认数据
    const defaultData = [
      {value: 335, name: '围栏预警', warnType: 1},
      {value: 310, name: '聚集预警', warnType: 2},
      {value: 234, name: '出入杭预警', warnType: 3},
      {value: 24, name: '接入预警', warnType: 4},
    ];
    set(pieOptionsData, 'legend.data', defaultData.map(v => t(v.name)));
    pieOptionsData.series![0].data = defaultData.map(v => ({
      name: t(v.name),
      value: v.value
    }));
  }
}


// 周活跃量图表
const getWeeklyUserActivity = async () => {
  const data = [
    {value: 13253, name: 'analysis.monday'},
    {value: 34235, name: 'analysis.tuesday'},
    {value: 26321, name: 'analysis.wednesday'},
    {value: 12340, name: 'analysis.thursday'},
    {value: 24643, name: 'analysis.friday'},
    {value: 1322, name: 'analysis.saturday'},
    {value: 1324, name: 'analysis.sunday'}
  ]
  set(barOptionsData, 'xAxis.data', data.map((v) => t(v.name)))
  set(barOptionsData, 'series', [
    {
      name: t('analysis.activeQuantity'),
      data: data.map((v) => v.value),
      type: 'bar',
      label: {
        show: true,
        position: 'top'
      }
    }
  ])
}

/** 打开聚集预警详情页，传递完整行记录 */
const openGatherDetail = (row: WarnCommon) => {
  try {
    // 1. 再次确认id存在（排除id类型问题）
    if (row.gatherId === undefined || row.gatherId === null) {
      throw new Error('记录ID不存在，无法打开详情')
    }

    // 2. 单独序列化row，确保无异常（排查序列化失败）
    let rowDataStr: string;
    try {
      rowDataStr = JSON.stringify(row);
      // console.log('序列化后的数据:', rowDataStr); // 确认序列化结果
    } catch (serialError) {
      throw new Error(`数据序列化失败: ${(serialError as Error).message}`);
    }

    // 3. 编码并传递参数
    router.push({
      name: 'WarningGatherPerson',
      params: {
        id: row.gatherId.toString(), // 匹配路由的:id参数
      },
      query: {
        rowData: encodeURIComponent(rowDataStr) // 确保添加到query
      }
    });

    // // 4. 验证跳转参数
    // console.log('跳转参数:', {
    //   params: {id: row.gatherId.toString()},
    //   query: {rowData: encodeURIComponent(rowDataStr)}
    // });

  } catch (error) {
    console.error('打开详情失败:', error);
    message.error(`打开详情失败: ${(error as Error).message}`);
  }
};

// 初始化所有数据
const getAllApi = async () => {
  try {
    loading.value = true
    await Promise.all([
      getCount(),
      getList(),
      getWarnPage(),
      getShortcut(),
      getWarnTypePie(),
      getWeeklyUserActivity()
    ])
  } finally {
    loading.value = false
  }
}

// 页面激活时重新加载数据
const reloadData = () => {
  if (!caseData.value) {
    fetchCaseData(String(route.params.id))
  }
  getAllApi()
}

onMounted(reloadData)
// onActivated(reloadData)
</script>

<style lang="scss" scoped>
.description-content {
  line-height: 1.6;
  padding: 8px;
  background: #f8f8f8;
  border-radius: 4px;
}

:deep(.person-pagination) {
  .el-pager {
    li {
      width: 24px;
      height: 24px;
      line-height: 24px;
      border-radius: 50%;
      margin: 0 4px;

      &.active {
        background: var(--el-color-primary);
        color: white;
      }

      &:hover {
        background: var(--el-color-primary-light-9);
      }
    }
  }

  .btn-prev,
  .btn-next {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    padding: 0;
    min-width: auto;

    &:hover {
      background: var(--el-color-primary-light-9);
    }
  }
}

.case-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 16px;
}

.case-description {
  font-size: 16px;
  line-height: 1.6;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.add-btn {
  padding: 0 12px;
  height: 28px;
  font-size: 14px;
  border-radius: 4px;
  background-color: #f5f5f5;
}

/* 阴影分隔线样式 */
.header-divider {
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(0, 0, 0, 0.1), transparent);
  margin: 12px 0 16px 0;
  width: 100%;
}

.items-start {
  margin-top: 10px;
}

/* 调整抽屉样式 */
:deep(.el-drawer__body) {
  padding-top: 0 !important;
}

:deep(.el-drawer__header) {
  font-weight: bold;
  margin-bottom: 0 !important;
}
:deep(.el-divider--horizontal){
  margin: 13px 0 !important;
}
.highlight-content {
  color: #333; // 与type和title保持一致的颜色
  // 如果需要单独设置高亮文本的颜色
  :deep(.highlight) {
    color: #409eff; // 高亮文本的颜色
    font-weight: 500;
  }
}
</style>
